<template>
  <a-modal v-bind:visible="isShowSendMessage" width="50%" title="发送短信" @cancel="onCancel">
    <a-spin :spinning="loading">
      <div class="content">
        <div class="left">
          <span>短信类型</span>
          <br />
          <a-select v-model="value" style="width: 150px; margin: 10px 0">
            <a-select-option v-for="item in templateType" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
          <br />
          <span>短信内容</span>
          <br />
          <p style="margin: 10px 0">{{ text }}</p>
          <div v-if="relation_id">
            <span>发送人</span>
            <div style="display: flex; margin: 10px 0">
              <a-input v-model="form.name" placeholder="发送人姓名"></a-input>
              <span style="margin: 0 10px"> - </span>
              <a-input v-model="form.phone" placeholder="发送人手机号"></a-input>
            </div>
            <span> 发送状态 </span>
            <div style="margin: 10px 0">
              <span>{{ form.send_status_text }}</span>
              <span style="margin: 0 5px"> - </span>
              <span>{{ form.utime }}</span>
            </div>
          </div>
          <span>发送内容</span>
          <br />
          <a-textarea v-model="form.content" style="margin: 10px 0" placeholder="" :rows="4" />
        </div>
        <div class="right">
          <a-button style="margin-bottom: 10px" @click="addTemplate"> 添加模板 </a-button>
          <a-table
            style="height: 350px; overflow-y: auto; border: 1px solid #e8e8e8"
            :rowKey="(record, index) => index"
            :columns="columns"
            :data-source="tableData"
            :pagination="false"
          >
            <template slot="title">
              <div @click="sort" style="cursor: pointer"></div>
            </template>
            <template slot="Title">
              <div style="cursor: pointer" @click="sort">
                <span v-if="sortBoo">排序</span>
                <a-icon type="check" v-if="!sortBoo" @click.stop="saveSort()"></a-icon>
              </div>
            </template>
            <span slot="sort" slot-scope="text, record">
              <span v-if="sortBoo" style="cursor: pointer" @click="sort()">{{ record.weight }}</span>
              <a-input-number style="width: 60px" v-else size="small" v-model="record.weight" />
            </span>
            <span slot="name" slot-scope="text, record">
              <div class="flexStyle" v-if="record.nameBoo">
                <span>{{ record.name }}</span>
                <a-icon class="editStyle" type="edit" @click="editName('name', record.id)" />
              </div>
              <div class="flexStyle" v-else>
                <a-input :allowClear="true" style="width: 150px" size="small" v-model="record.name"></a-input>
                <a-icon type="check" @click="saveName(record.id, record.name, record.content)" />
              </div>
            </span>
            <span slot="content" slot-scope="text, record">
              <div class="flexStyle" v-if="record.contentBoo">
                <span @click="sendContent(record.content)">{{ record.content }}</span>
                <a-icon class="editStyle" type="edit" @click="editName('content', record.id)" />
              </div>
              <div class="flexStyle" v-else>
                <a-input :allowClear="true" style="width: 150px" size="small" v-model="record.content"></a-input>
                <a-icon type="check" @click="saveName(record.id, record.name, record.content)" />
              </div>
            </span>
            <span slot="operate" slot-scope="text, record">
              <span class="rateStyle" @click="del(record.id)">删除</span>
            </span>
          </a-table>
        </div>
      </div>
    </a-spin>
    <template slot="footer">
      <a-button type="primary" @click="send"> 发送 </a-button>
    </template>
  </a-modal>
</template>

<script>
import {
  getMessageTemplateAPI,
  getMessageListAPI,
  editMessageNameAPI,
  sortAPI,
  delMessageTemplateAPI,
  addTemplateAPI,
  sendInfoAPI,
  sendMessage
} from '@/api/userinfo.js'
export default {
  name: 'SendMessage',
  props: {
    isShowSendMessage: {
      type: Boolean,
      default: false
    },
    ids: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    async isShowSendMessage(boolean) {
      if (boolean) {
        this.getList()
      }
    }
  },
  data() {
    return {
      loading: false,
      sortBoo: true,
      value: '',
      templateType: [],
      text: '',
      form: {
        name: '',
        phone: '',
        send_status_text: '',
        utime: '',
        content: ''
      },
      fromData: {
        order: 'desc',
        order_by: 'id',
        page: '1',
        page_size: 50,
        search: {
          brand_id: process.env.VUE_APP_BRAND_ID,
          name: '',
          scene: 2
        }
      },
      columns: [
        {
          title: '#',
          dataIndex: 'id',
          align: 'center'
        },
        {
          dataIndex: 'weight',
          align: 'center',
          scopedSlots: { customRender: 'sort', title: 'Title' }
        },
        {
          title: '短信名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '短信内容',
          dataIndex: 'content',
          align: 'center',
          scopedSlots: { customRender: 'content' }
        },
        {
          title: '操作',
          align: 'center',
          scopedSlots: { customRender: 'operate' }
        }
      ],
      tableData: []
    }
  },
  methods: {
    sendContent(content) {
      this.form.content = content
    },
    async getList() {
      const array = [
        getMessageTemplateAPI({ brand_id: process.env.VUE_APP_BRAND_ID }),
        getMessageListAPI(this.fromData)
      ]
      try {
        this.loading = true
        const [result, message] = await Promise.all(array)
        this.templateType = result.data
        this.value = this.templateType && this.templateType[0].id
        this.text = this.templateType && this.templateType[0].content
        this.tableData = message.data.list.map(item => {
          item.nameBoo = true
          item.contentBoo = true
          return item
        })
        if (this.relation_id) {
          const { data } = await sendInfoAPI({
            brand_id: process.env.VUE_APP_BRAND_ID,
            relation_id: this.relation_id,
            scene_type: 2
          })
          this.form.name = data.realname
          this.form.phone = data.phone
          this.form.utime = data.utime || '暂无'
          this.form.send_status_text = data.send_status_text || '暂无'
          this.form.content = data.original_data.content
        }
      } finally {
        this.loading = false
      }
    },
    onCancel() {
      this.$emit('update:isShowSendMessage', false)
      this.$emit('update:relation_id', undefined)
    },
    async send() {
      if (!this.form.content) return this.$message.error('请输入短信内容')
      let form = {}
      if (this.ids.length > 0) {
        form = {
          brand_id: process.env.VUE_APP_BRAND_ID,
          content: this.form.content,
          ids: this.ids,
          send_scene: 8,
          template_type: this.templateType[0].id
        }
      } else {
        form = {
          brand_id: process.env.VUE_APP_BRAND_ID,
          content: this.form.content,
          ids: this.relation_id,
          send_scene: 8,
          template_type: this.templateType[0].id
        }
      }

      try {
        await sendMessage(form)
        this.$emit('upload')
        this.$emit('update:isShowSendMessage', false)
        this.$emit('update:relation_id', undefined)
        this.$message.success('发送成功')
      } catch (err) {
        this.$message.error(err.data.msg)
      }
    },
    editName(value, id) {
      this.tableData = this.tableData.map(item => {
        if (item.id === id) {
          if (value === 'name') {
            item.nameBoo = false
          } else if (value === 'content') {
            item.contentBoo = !item.contentBoo
          }
        }
        return item
      })
    },
    async addTemplate() {
      const form = {
        brand_id: process.env.VUE_APP_BRAND_ID,
        content: '点击右侧图标修改文字',
        name: '点击右侧图标修改文字',
        scene: 2
      }
      await addTemplateAPI(form)
      this.getList()
      this.$message.success('添加成功')
    },
    async saveName(id, name, content) {
      const form = {
        brand_id: process.env.VUE_APP_BRAND_ID,
        content: content,
        ids: id,
        name: name
      }
      try {
        await editMessageNameAPI(form)
        this.getList()
        this.sortBoo = true
        this.$message.success('修改成功')
      } catch (error) {
        this.$message.error(error.data.msg)
      }
    },
    del(id) {
      this.$confirm({
        title: '您确定要删除此模板吗?',
        content: h => <div style="color:red;">此操作不可撤回</div>,
        onOk: async () => {
          await delMessageTemplateAPI({ brand_id: process.env.VUE_APP_BRAND_ID, ids: id })
          this.getList()
          this.$message.success('删除成功')
        },
        onCancel() {
          return
        }
      })
    },
    async saveSort() {
      const array = this.tableData.map(item => {
        return { id: item.id, weight: item.weight }
      })
      await sortAPI(array)
      this.sortBoo = true
      this.getList()
      this.$message.success('修改成功')
    },
    sort() {
      if (this.sortBoo) {
        this.sortBoo = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.content {
  display: flex;
  .left {
    margin-right: 20px;
    width: 30%;
  }
  .right {
    flex: 1;
    width: (70% - 20);
  }
}
.rateStyle {
  cursor: pointer;
  color: #1890ff;
}

/deep/ .ant-table-wrapper::-webkit-scrollbar {
  width: 5px;
  height: 6px;
}

/deep/ .ant-table-wrapper::-webkit-scrollbar-thumb {
  border-radius: 3px;
  background: #1890ff;
}

/deep/ .ant-table-wrapper::-webkit-scrollbar-track {
  border-radius: 1px;
  background: #f1f1f1;
}
.flexStyle {
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  .editStyle {
    visibility: hidden;
  }
}
.flexStyle:hover {
  .editStyle {
    visibility: visible;
  }
}
</style>
